package com.eslserver.action.helper;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.core.config.HTTPServerConfig;
import com.eslserver.servletapi.input.PushESLServletInputParam;
import com.eslserver.servletapi.response.PushESLDisplayReturnValue;
import com.eslserver.to.Coordinator;
import com.eslserver.to.ESL;
import com.eslserver.to.Image;

public class PushESLHTTPMultipartPost implements PushESLServletInputParam,
		PushESLDisplayReturnValue {
	static final Logger LOG = LoggerFactory
			.getLogger(PushESLHTTPMultipartPost.class);

	private ESL esl;
	private int sleeptime;
	private Coordinator coordinator;
	private Image eslImage;

	public PushESLHTTPMultipartPost(ESL esl, Coordinator coordinator,
			Image eslImage) {
		this.esl = esl;
		this.coordinator = coordinator;
		this.eslImage = eslImage;
	}

	public PushESLHTTPMultipartPost(ESL esl, Coordinator coordinator,
			Image eslImage, int sleeptime) {
		this.esl = esl;
		this.sleeptime = sleeptime;
		this.coordinator = coordinator;
		this.eslImage = eslImage;
	}

	public StringBuffer sendHTTPPost() throws ClientProtocolException,
			IOException {
		StringBuffer pushMessage = new StringBuffer();

		HttpPost method = new HttpPost(HTTPServerConfig.urlPath
				+ "/PushESLDisplayServlet.do");
		MultipartEntity entity = new MultipartEntity();
		Charset utf8 = Charset.forName("UTF-8");
		entity.addPart(COORDINATOR_IP_ADDRESS,
				new StringBody(coordinator.getIpAddress(), utf8));
		entity.addPart(COORDINATOR_PORT, new StringBody(coordinator.getPort()
				.toString(), utf8));
		entity.addPart(ESL_MAC_ADDRESS, new StringBody(esl.getMacAddress(),
				utf8));
		entity.addPart(ESL_SLEEP_TIME, new StringBody(
				String.valueOf(sleeptime), utf8));

		pushMessage.append(esl.getName());
		if (eslImage != null) {
			File f = new File(eslImage.getSystemPath());

			if (f.exists()) {
				DefaultHttpClient httpclient = new DefaultHttpClient();
				FileBody fileBody = new FileBody(f);
				entity.addPart("file", fileBody);
				method.setEntity(entity);
				HttpResponse response = httpclient.execute(method);
				LOG.debug(response.getStatusLine().toString());

				InputStream is = response.getEntity().getContent();
				StringWriter writer = new StringWriter();
				IOUtils.copy(is, writer, utf8.toString());
				String responseBody = writer.toString();
				LOG.debug(responseBody);

				if (responseBody.equals(CONNECTION_FAIL)) {
					pushMessage.append(": Connection failed." + "</br>");
				} else if (responseBody.equals(ERROR)) {
					pushMessage
							.append(": Unknown error has occured but part of display may have changed."
									+ "</br>");
				} else if (responseBody.equals(INVALID_FILE)) {
					pushMessage.append(": Invalid image file provided."
							+ "</br>");
				} else if (responseBody.equals(OK)) {
					pushMessage.append(": Command successful." + "</br>");
				}
			} else {
				pushMessage.append(": Local image file does not exist."
						+ "</br>");
			}
		} else {
			pushMessage.append(": Image not uploaded." + "</br>");
		}

		return pushMessage;
	}
}
